package com.jin.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jin.common.to.es.SeckillOrderTo;
import com.jin.common.utils.R;
import com.jin.common.vo.MemberRespVo;
import com.jin.gulimall.seckill.feign.CouponFeign;
import com.jin.gulimall.seckill.feign.ProductFeign;
import com.jin.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.jin.gulimall.seckill.service.SeckillService;
import com.jin.gulimall.seckill.to.SeckillRedisTo;
import com.jin.gulimall.seckill.vo.SeckillSessionWithSkusVo;
import com.jin.gulimall.seckill.vo.SkuInfoVo;
import lombok.AllArgsConstructor;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.security.Key;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeign couponFeign;

    @Autowired
    ProductFeign productFeign;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    StringRedisTemplate redisTemplate;

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";
    private final String SECKILLSKU_CACHE_PREFIX = "seckill:skus";
    //Semaphore
    private final String SECKILL_STOCK_SEMAPHORE = "seckill:stock:";
    private Long startTime;

    @Override
    public void uploadSeckillSku3Days() {
        //将接下来三天要秒杀的商品进行上架
        R r = couponFeign.getSeckillSkuLatest3Days();
        if (r.getCode() == 0) {
            List<SeckillSessionWithSkusVo> sessionData = r.getData(new TypeReference<List<SeckillSessionWithSkusVo>>() {
            });
            //缓存到redis
            //缓存活动信息
            saveSessionInfos(sessionData);
            //缓存活动关联的商品信息
            saveSessionSkuInfos(sessionData);
        }
    }

    /**
     * 获取当前时间需要秒杀的所有商品
     *
     * @return
     */
    @Override
    public List<SeckillRedisTo> getCurrentSeckillSkus() {
        //1.确定当前时间属于哪个秒杀场次
        long currentTime = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                //seckill:sessions:1627563600000_1627567200000
                String s = key.replace(SESSION_CACHE_PREFIX, "");
                String[] strings = s.split("_");
                long startTime = Long.parseLong(strings[0]);
                long endTime = Long.parseLong(strings[1]);
                if (currentTime >= startTime && currentTime <= endTime) {
                    //2.获取这个秒杀场次需要的所有商品信息
                    List<String> list = redisTemplate.opsForList().range(key, -100, 100);
                    if (list != null && list.size() > 0) {
                        //获取1_1 , 2_2 2_16 等对应的sku信息
                        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILLSKU_CACHE_PREFIX);
                        List<String> stringList = hashOps.multiGet(list);
                        if (stringList != null && stringList.size() > 0) {
                            List<SeckillRedisTo> collect = stringList.stream().map(item -> {
                                SeckillRedisTo redisTo = JSON.parseObject(item, SeckillRedisTo.class);
                                return redisTo;
                            }).collect(Collectors.toList());
                            return collect;
                        }
                    }
                    break;
                }
            }
        }
        return null;
    }

    @Override
    public SeckillRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILLSKU_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SeckillRedisTo redisTo = JSON.parseObject(json, SeckillRedisTo.class);
                    //随机码处理
                    long currentTime = new Date().getTime();
                    Long endTime = redisTo.getEndTime();
                    Long startTime = redisTo.getStartTime();
                    if (currentTime >= startTime && currentTime <= endTime) {
                    } else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }

    /**
     * 开始真正的秒杀
     *
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo memberRespVo = LoginUserInterceptor.threadLocal.get();
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILLSKU_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (!StringUtils.isEmpty(json)) {
            //校验合法性
            SeckillRedisTo redisTo = JSON.parseObject(json, SeckillRedisTo.class);
            Long startTime = redisTo.getStartTime();
            Long endTime = redisTo.getEndTime();
            long ttl = endTime - startTime;
            long time = new Date().getTime();
            //1.校验时间的合法性
            if (time >= startTime && time <= endTime) {
                //2.校验随机码和商品id
                String skuId = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
                String randomCode = redisTo.getRandomCode();
                if (key.equals(randomCode) && killId.equals(skuId)) {
                    //3.验证购物数量是否合理
                    if(num<=redisTo.getSeckillLimit()){
                        //4.验证该用户是否购买过 key:userId_sessionId_skuId
                        String redisKey = memberRespVo.getId() + "_" + skuId;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if(aBoolean){
                            //占位成功，说明从来没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SECKILL_STOCK_SEMAPHORE + randomCode);
                            boolean b = semaphore.tryAcquire(num);
                            if(b){
                                //获取信号量成功，即抢到秒杀商品
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setOrderSn(timeId);
                                orderTo.setNum(num);
                                orderTo.setMemberId(memberRespVo.getId());
                                orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                orderTo.setSkuId(redisTo.getSkuId());
                                orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);
                                return timeId;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    //缓存活动关联的商品信息
    private void saveSessionSkuInfos(List<SeckillSessionWithSkusVo> sessions) {
        if (sessions != null && sessions.size() > 0) {
            sessions.stream().forEach(session -> {
                //准备操作hash
                BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SECKILLSKU_CACHE_PREFIX);
                session.getRelationSkus().forEach(sku -> {
                    if (!ops.hasKey(sku.getPromotionSessionId().toString() + "_" + sku.getSkuId().toString())) {
                        //缓存商品
                        SeckillRedisTo redisTo = new SeckillRedisTo();
                        //1.sku基本数据
                        Long skuId = sku.getSkuId();
                        R info = productFeign.getSkuInfo(skuId);
                        if (info.getCode() == 0) {
                            SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            redisTo.setSkuInfo(skuInfo);
                        }
                        //2.sku秒杀数据
                        BeanUtils.copyProperties(sku, redisTo);
                        //3.设置商品的秒杀时间信息
                        redisTo.setStartTime(session.getStartTime().getTime());
                        redisTo.setEndTime(session.getEndTime().getTime());
                        //4.随机码
                        String token = UUID.randomUUID().toString().replace("-", "");
                        redisTo.setRandomCode(token);
                        //5.使用库存作为分布式的信号量
                        RSemaphore semaphore = redissonClient.getSemaphore(SECKILL_STOCK_SEMAPHORE + token);
                        //商品可以秒杀的数量作为信号量
                        semaphore.trySetPermits(sku.getSeckillCount().intValue());

                        String s = JSON.toJSONString(redisTo);
                        ops.put(sku.getPromotionSessionId().toString() + "_" + sku.getSkuId().toString(), s);
                    }
                });
            });
        }
    }

    //缓存活动信息
    private void saveSessionInfos(List<SeckillSessionWithSkusVo> sessions) {
        if (sessions != null && sessions.size() > 0) {
            sessions.stream().forEach(session -> {
                Long startTime = session.getStartTime().getTime();
                Long endTime = session.getEndTime().getTime();
                String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
                //将信息放入到redis中
                if (!redisTemplate.hasKey(key)) {
                    //每个活动对应的skuIds
                    List<String> skuIds = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key, skuIds);
                }
            });
        }
    }
}
